const express = require("express");
const conn = require("./mysql.js");
const app = express();
const port = 8080;

// 用户账号和密码
const users = [ { username: 'admin', password: 'password123' } ];

app.get("/login" , (req , res) => {
  // 判断
  // let user = users.find(u => u.username == req.query.username && u.password == req.query.pwd1)
  // console.log(user)
  
  // 通过连接对象执行连接
  conn.connect((err) => {
    if (err) {
      console.error("1." + err.message);
    } else {
      console.log("1.连接成功！");
    }
  });

  // 定义SOL查询
  let sql = "select * from user where username = '" + req.query.username + "' and password='" + req.query.pwd1 + "'; ";

  // 执行SQL
  conn.query(sql, (err, result) => {
    if (err) {
      console.error("2." + err.message);
    } else {
      // console.log(result);
      if(result.length > 0){
        // 用户名和密码正确
        res.json( {code: 200 ,msg:"登录成功"});
        }else{
        // 用户名或密码错误
        res.json({code:401,msg:"登录失败"});
        }
    }
  });

})

app.listen(port, () => {
  console.log("监听端口" + port);
});